package cn.linlane.service.sys;

import cn.linlane.dao.sys.SysAuthDao;
import cn.linlane.entity.sys.SysAuth;
import cn.linlane.entity.sys.SysDepart;
import cn.linlane.entity.sys.SysRole;
import cn.linlane.entity.sys.SysUser;
import cn.linlane.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysAuthService extends BaseService<SysAuthDao, SysAuth> {

    @Autowired
    private ShiroService shiroService;

    public Set<SysAuth> findAllSysAuthsById(Set<Integer> authIds){
        return baseDao.findAllByIdIn(authIds);
    }

    /**
     * 获取当前用户全部权限的树
     * @return
     */
    public Set<SysAuth> getCurrentAuth(){

        SysUser sysUser = shiroService.getSysUser();

        Set<Integer> authIds = new HashSet<>();

        Set<SysRole> sysRoles = sysUser.getSysRoles();
        for (SysRole sysRole : sysRoles) {
            //获取角色
            for (SysAuth sysAuth : sysRole.getSysAuths()){
                //获取权限
                authIds.add(sysAuth.getId());
            }
        }

        Set<SysAuth> sysAuths = baseDao.findAllByIdIn(authIds);

        //返回前端树
        Set<SysAuth> frontAuths = new HashSet<>();

        for (SysAuth sysAuth : sysAuths){
            if (sysAuth.getParentNodeId() == null){
                frontAuths.add(sysAuth);
            }
        }

        getChild(frontAuths, sysAuths);

        return frontAuths;
    }


    /**
     * 获取全部权限的树
     * @return
     */
    public Set<SysAuth> getAllAuth(){

        Set<SysAuth> sysAuthList = baseDao.findAllSet();

        //返回前端树
        Set<SysAuth> frontAuths = new HashSet<>();

        for (SysAuth sysAuth : sysAuthList){
            if (sysAuth.getParentNodeId() == null){
                frontAuths.add(sysAuth);
            }
        }

        getChild(frontAuths, sysAuthList);

        return frontAuths;
    }

    /**
     * 递归
     * @return
     */
    public List<SysDepart> getChild(Set<SysAuth> frontAuths, Set<SysAuth> sysAuths){

        if (frontAuths.size() == 0){
            return null;
        }else {
            Set<SysAuth> auths = new HashSet<>();

            for (SysAuth sysAuth : frontAuths){

                Set<SysAuth> sysAuthHashSet = new HashSet<>();

                for (SysAuth sysAuth1 : sysAuths){
                    if (sysAuth.getId().equals(sysAuth1.getParentNodeId())){
                        sysAuthHashSet.add(sysAuth1);
                    }
                }
                if (sysAuthHashSet.size() > 0){
                    sysAuth.setSysAuths(sysAuthHashSet);
                }
                auths.addAll(sysAuthHashSet);
            }
            return getChild(auths, sysAuths);
        }
    }
}
